﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using FDSimpleModelGenerator.Common.Enums;

namespace FDSimpleModelGenerator.Common.HtmlConvert
{
    /// <summary>
    /// 基类符号处理
    /// </summary>
    public abstract class BasicSymbolHtml : ILanguageSymbolHtml
    {
        /// <summary>
        /// 语言数据类型
        /// </summary>
        public abstract LanguageDataType LanguageDataType { get; }

        /// <summary>
        /// 所有关键字
        /// </summary>
        public abstract IList<string> Keywords { get; }

        /// <summary>
        /// 关键字着色 #0000ff
        /// </summary>
        public abstract string KeywordColor { get; }

        /// <summary>
        /// 关键字替换字典
        /// </summary>
        private readonly Dictionary<string, string> KeywordReplaceData = new Dictionary<string, string>();

        public BasicSymbolHtml()
        {
            foreach (var keyword in Keywords)
            {
                KeywordReplaceData[keyword] = $"<span style=\"color:{KeywordColor};\">{keyword}</span>";
            }
        }

        /// <summary>
        /// 替换处理
        /// </summary>
        /// <returns></returns>
        public virtual string ReplaceClsType(string content)
        {
            var regHtml = new Regex("(<.+>)");
            var htmlMatches = regHtml.Matches(content).Select(m => m.Value).Distinct();

            content = content.Replace("\t", "".PadLeft(4)).Replace(" ", "&nbsp;");
            foreach (var htmlMatch in htmlMatches)
            {
                content = content.Replace(htmlMatch, HttpUtility.HtmlEncode(htmlMatch));
            }
            foreach (var keyword in Keywords)
            {
                var keyData = KeywordReplaceData[keyword];
                content = content.ReplaceWholeWord(keyword, keyData)
                    .Replace("\r\n", "<br/>")
                    .Replace("\n", "<br/>");
            }

            return content;
        }
    }
}
